/**
 * Project Name:b2c-app
 * File Name:TokenServiceImpl.java
 * Package Name:cn.bluemobi.app.service.impl
 * Date:2016年1月20日下午5:11:15
 * Copyright (c) 2016, bluemobi.cn All Rights Reserved.
 *
 */

package cn.bluemobi.app.service.impl;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import org.apache.commons.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

import cn.bluemobi.app.core.utils.AppConstants;
import cn.bluemobi.app.entity.output.Member;
import cn.bluemobi.app.service.TokenService;
import cn.bluemobi.common.utils.HmacsHa1;
import cn.bluemobi.common.utils.MD5Tools;

/**
 * Description: <br/>
 * Date: 2016年1月20日 下午5:11:15 <br/>
 * 
 * @author hut
 * @version
 * @see
 */
@Service
public class TokenServiceImpl implements TokenService {

	@Autowired
	private EhCacheCacheManager cacheManager;

	@Override
	public String createToken(Member member) {
		String token = getToken(member.getMemberId());
		cacheManager.getCache("tokenCache").put(token, member);
		return token;
	}

	@Override
	public Member validateToken(String token) {
		ValueWrapper wrapper = cacheManager.getCache("tokenCache").get(token);
		if (wrapper == null) {
			return null;
		}
		Object obj = wrapper.get();
		if (obj == null) {
			return null;
		}
		return (Member) obj;
	}

	@Override
	public int evict(String token) {
		cacheManager.getCache("tokenCache").evict(token);
		return 0;
	}

	private String getToken(String string) {
		// 随机生成一个字符串
		String content = MD5Tools.encode(UUID.randomUUID().toString() + string);
		String sign = "";
		// 加签名
		try {
			sign = HmacsHa1.getSignature(content, AppConstants.TOKEN_KEY);
		} catch (InvalidKeyException | NoSuchAlgorithmException
				| UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return content + sign;
	}

	@Override
	public boolean checkTokenSign(String token) {
		String content = token.substring(0, 32);
		String sign = token.substring(32);
		try {
			if (StringUtils.equals(sign,
					HmacsHa1.getSignature(content, AppConstants.TOKEN_KEY))) {
				return true;
			} else {
				return false;
			}
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return false;
	}
}
